import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '@/stores/auth'
import Layout from '@/components/Layout.vue'
import LoginView from '@/views/LoginView.vue'

// 基础路由（不需要权限的路由）
const constantRoutes = [
  {
    path: '/login',
    name: 'login',
    component: LoginView,
    meta: { requiresAuth: false }
  },
  {
    path: '/',
    name: 'layout',
    component: Layout,
    redirect: '/dashboard',
    meta: { requiresAuth: true },
    children: [
      {
        path: 'dashboard',
        name: 'dashboard',
        component: () => import('@/views/Dashboard.vue'),
        meta: { title: '仪表盘' }
      }
    ]
  }
]

// 动态获取组件
function getComponentByPath(path) {
  try {
    // 处理路径，去掉开头的斜杠
    const cleanPath = path.startsWith('/') ? path.substring(1) : path
    // 特殊情况：dashboard 直接返回
    if (cleanPath === 'dashboard') {
      return () => import('@/views/Dashboard.vue')
    }

    // 解析路径结构
    const pathParts = cleanPath.split('/')
    if (pathParts.length === 1) {
      // 一级菜单目录 - 这些通常不需要组件
      return null
    } else if (pathParts.length >= 2) {
      // 二级及以上菜单，直接使用URL路径结构映射到views目录
      const [category, page] = pathParts
      // 将页面名转换为组件名（首字母大写）
      let componentName = page.charAt(0).toUpperCase() + page.slice(1)
      const componentKey = `${category}/${componentName}`
      // 动态导入组件
      try {
        return () => import(`@/views/${category}/${componentName}.vue`)
      } catch (error) {
        return null
      }
    }
    return null
  } catch (error) {
    return null
  }
}

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: constantRoutes
})

// 生成动态路由
function generateRoutes(menus) {
  const routes = []

  function processMenu(menu) {
    // 只为有实际页面组件的菜单生成路由（二级菜单或特殊的一级页面如dashboard）
    if (menu.path && !menu.children) {
      // 这是一个叶子节点菜单，尝试生成路由
      const component = getComponentByPath(menu.path)
      if (component) {
        const routePath = menu.path.startsWith('/') ? menu.path.substring(1) : menu.path
        routes.push({
          path: '/' + routePath,
          name: routePath.replace(/\//g, '-'),
          component: component,
          meta: {
            title: menu.name,
            icon: menu.icon || '',
            id: menu.id,
            path: menu.path
          }
        })
      }
    }

    // 递归处理子菜单
    if (menu.children && menu.children.length > 0) {
      menu.children.forEach(child => {
        processMenu(child)
      })
    }
  }

  menus.forEach(menu => processMenu(menu))
  return routes
}

// 添加动态路由
function addDynamicRoutes(menus) {
  const dynamicRoutes = generateRoutes(menus)
  // 将动态路由添加为 Layout 的子路由
  dynamicRoutes.forEach(route => {
    // 移除路径开头的 '/' 因为这些是子路由
    const childRoute = {
      ...route,
      path: route.path.startsWith('/') ? route.path.substring(1) : route.path
    }
    router.addRoute('layout', childRoute)
  })
}

// 路由守卫
router.beforeEach(async (to) => {
  const authStore = useAuthStore()

  if (to.meta.requiresAuth !== false && !authStore.isAuthenticated) {
    return '/login'
  }

  if (to.path === '/login' && authStore.isAuthenticated) {
    return '/'
  }

  // 如果已登录但菜单为空（刷新页面时可能发生）
  if (authStore.isAuthenticated && authStore.userMenus.length === 0) {
    try {
      const result = await authStore.getCurrentUser()
      if (result.success && authStore.userMenus.length > 0) {
        addDynamicRoutes(authStore.userMenus)
        // 如果当前访问的不是首页，重新路由到目标页面
        if (to.path !== '/' && to.path !== '/dashboard') {
          return to.fullPath
        }
      }
    } catch (error) {
      authStore.logout()
      return '/login'
    }
  }
})

export default router
